import {reqSendCode,reqRegister,reqLogin,reqGetUserInfo,reqLogOut} from '@/api'
import { setToken,getToken,clearToken} from '@/utils/token'
const state = {
    code:'',
    token:getToken(),
    userInfo:{}
}
const actions = {
    // 验证码
   async getCode({commit},phone){
       let result = await reqSendCode(phone)
      if(result.code == 200){
          commit('GETCODE',result.data)
          return 'ok'
      }else{
          return Promise.reject(new Error('faile'))
      }
   },
    //   注册用户
     async succeedRegister({commit},{phone,code,password}){
         let result = await reqRegister(phone,code,password);
         if(result.code == 200){
             return 'ok'
         }else{
             return Promise.reject(result.message)
         }
     },
    //  用户登录
    async login({commit},{phone,password}){
        let result = await reqLogin(phone,password);
        if(result.code == 200){
            commit('LOGIN',result.data.token)
            setToken(result.data.token);
            return 'ok'
        }else{
            return Promise.reject(result.message)
        }
    },
    // 得到用户信息
    async getUserInfo({commit}){
        let result = await reqGetUserInfo();
        if(result.code == 200){
            commit('GETUSERINFO',result.data)
        }
    },
    // 退出登录
    async loginOut({commit}){
        let result = await reqLogOut();
        if(result.code == 200){
            commit('LOGINOUT')
        }
    }
}
const mutations ={
    // 验证码
    GETCODE(state,code){
            state.code = code
    },
    // token  登录返回的
    LOGIN(state,token){
        state.token = token;
    },
    // 获取用户信息
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    // 退出登录需要把 token 清空 用户信息清空 清除本地存储
    LOGINOUT(state){
        state.token = "";
        state.userInfo = {};
        clearToken();
    }
}
const getters = {}
export default {
    state,
    actions,
    mutations,
    getters
}